﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;

namespace CssCrawler
{
    public partial class FrmMain : Form
    {
        delegate void BindTextBoxControl(string text);
        private List<string> list;
        public FrmMain()
        {
            InitializeComponent();
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            if (folderDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtFolder.Text = folderDlg.SelectedPath;
            }
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            if (!bgWorker.IsBusy)
            {
                txtLog.Text = "Start \r\n";
                bgWorker.RunWorkerAsync();
            }
        }

        /// <summary>
        /// Returns the content of a given web adress as string.
        /// </summary>
        /// <param name="Url">URL of the webpage</param>
        /// <returns>Website content</returns>
        public string DownloadWebPage(string Url)
        {
            // Open a connection
            HttpWebRequest WebRequestObject = (HttpWebRequest)HttpWebRequest.Create(Url);

            // You can also specify additional header values like 
            // the user agent or the referer:
            WebRequestObject.UserAgent = ".NET Framework/2.0";
            WebRequestObject.Referer = "http://www.example.com/";

            // Request response:
            WebResponse Response = WebRequestObject.GetResponse();

            // Open data stream:
            Stream WebStream = Response.GetResponseStream();

            // Create reader object:
            StreamReader Reader = new StreamReader(WebStream);

            // Read the entire stream content:
            string PageContent = Reader.ReadToEnd();

            // Cleanup
            Reader.Close();
            WebStream.Close();
            Response.Close();

            return PageContent;
        }


        private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                string content = DownloadWebPage(txtUrl.Text);
                int leng = content.Length;
                int cur = content.IndexOf("url(");
                list = new List<string>();
                while (leng > cur && cur > 1)
                {

                    content = content.Substring(cur);
                    int last = content.IndexOf(")");
                    if (last > 0)
                    {
                        string temp = "";
                        if (content.StartsWith("url('") || content.StartsWith("url(\""))
                        {
                            temp = content.Substring(5, last - 6);
                        }
                        else
                        {
                            temp = content.Substring(4, last - 4);
                        }

                        list.Add(temp);
                        content = content.Substring(last + 1);
                        leng = content.Length;
                        cur = content.IndexOf("url(");
                    }
                    else
                    {
                        break;
                    }
                }

                string root = txtUrl.Text.Substring(0, txtUrl.Text.LastIndexOf("/") + 1);
                foreach (string item in list)
                {

                    string directory = item;
                    int l = directory.LastIndexOf("/");
                    directory = directory.Substring(0, l);
                    directory = directory.Replace("/", "\\");

                    //if(!file.StartsWith("\\")) file = "\\" + file;

                    string folder = txtFolder.Text + "\\";
                    string path = folder + directory;
                    EnsureDirectoryExists(path);

                    string dbfilename = item.Replace("/", "\\");
                    string filename = folder + dbfilename;
                    log("Download file " + filename + "\r\n");
                    // insert data base
                    
                    try
                    {
                        WebClient webClient = new WebClient();
                        webClient.DownloadFile(root + item, filename);
                        log("finished download file \r\n");
                    }
                    catch (Exception ex2)
                    {
                        log(ex2.Message + "\r\n");
                    }
                    
                }
                log("Finished");
            }
            catch (Exception ex)
            {
                log(ex.Message);
            }

        }

        //Method


        private void UpdateTextbox(string _Text)
        {

            txtLog.Text += _Text;

        }
        private void log(string text)
        {
            this.Invoke(new BindTextBoxControl(UpdateTextbox), new object[] { text });
        }

        private bool EnsureDirectoryExists(string path)
        {

            int i, startpoint = 0;
            String tmpPath = "";

            if (path.Substring(0, 2) == "\\")
            {
                startpoint = 3;
            }

            try
            {

                string[] dirArr = path.Split(new char[] { '\\' });

                for (i = 0; i < dirArr.Length; i++)
                {

                    tmpPath += dirArr[i] + "\\";

                    if (i >= startpoint)
                    {
                        if (!Directory.Exists(tmpPath))
                        {
                            Directory.CreateDirectory(tmpPath);
                        }
                    }
                }
            }
            catch
            {
            }


            if (Directory.Exists(path))
            {

                return true;
            }
            return false;

        }
    }
}
